package com.bookocean.infrastructure.persistence.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bookocean.domain.entity.UserParticipation;
import com.bookocean.domain.repository.UserParticipationRepository;
import com.bookocean.infrastructure.persistence.mapper.UserParticipationMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

/**
 * 用户参与记录仓储实现类
 * 
 * @author BookOcean
 * @since 2024-01-01
 */
@Repository
@RequiredArgsConstructor
public class UserParticipationRepositoryImpl implements UserParticipationRepository {

    private final UserParticipationMapper userParticipationMapper;

    @Override
    public UserParticipation findByUserIdAndQuizId(String userId, String quizId) {
        LambdaQueryWrapper<UserParticipation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserParticipation::getUserId, Long.valueOf(userId))
                .eq(UserParticipation::getQuizId, quizId);
        return userParticipationMapper.selectOne(wrapper);
    }

    @Override
    public UserParticipation findLatestByUserId(String userId) {
        LambdaQueryWrapper<UserParticipation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserParticipation::getUserId, Long.valueOf(userId))
                .orderByDesc(UserParticipation::getCreateTime)
                .last("LIMIT 1");
        return userParticipationMapper.selectOne(wrapper);
    }

    @Override
    public UserParticipation save(UserParticipation participation) {
        userParticipationMapper.insert(participation);
        return participation;
    }
}
